<template>
  <div>
    <GlobalHeader
      class="color-black position-fixed position-top-none w-full bg-white border-b border-b-solid border-b-zinc-1 z-50"
    ></GlobalHeader>

    <div class="m-t-84px flex justify-center gap20px">
      <!-- 左侧视频信息和操作栏 -->
      <div class="w-668px desktop:w-1086px">
        <!-- 视频信息 -->
        <el-skeleton style="width: 240px" :loading="videoInfoLoading" animated>
          <template #template>
            <div style="padding: 14px">
              <div class="min-h-78px m-b-10px">
                <el-skeleton-item
                  variant="text"
                  style="height: 30px; width: 50%"
                />
                <div class="flex gap20px m-t-10px m-b-20px">
                  <el-skeleton-item variant="text" class="w-60px" />
                  <el-skeleton-item variant="text" class="w-60px" />
                  <el-skeleton-item variant="text" class="w-200px" />
                  <el-skeleton-item variant="text" class="w-300px" />
                </div>
              </div>
            </div>
          </template>
          <template #default>
            <div min-h-78px m-b-10px>
              <p class="text-20px line-clamp-1 c-#18191c">
                {{ videoInfo?.title }}
              </p>

              <div class="c-#9499a0 text-13px m-t-10px m-b-20px">
                <span class="iconfont icon-shipin v-bottom m-r-2px"></span>
                {{ videoInfo?.playCount }}
                <span
                  class="iconfont icon-danmushu m-l-10px v-bottom m-l-10px m-r-2px"
                ></span>
                {{ videoInfo?.danmakuCount }}
                <span class="m-x-20px">{{ videoInfo?.createTime }}</span>
                <span v-if="videoInfo?.isRemix === 0">
                  <span
                    class="iconfont icon-jinzhi v-bottom c-red m-r-2px"
                  ></span>
                  <span>未经作者授权，禁止转载</span>
                </span>
              </div>
            </div>
          </template>
        </el-skeleton>

        <!-- video -->
        <div id="mse" class="!w-full !aspect-video"></div>

        <!-- 操作栏 -->
        <div class="flex flex-col shadow-[0_0_8px_#F1F2F3]">
          <div
            class="h-56px text-14px c-#61666d flex p-x-10px box-border gap-30px relative"
          >
            <span class="leading-56px">
              1人正在观看，已装填 {{ danmuDataList.length }} 条弹幕
            </span>
            <div class="flex-1 flex items-center leading-56px">
              <!-- 弹幕控制label -->
              <span
                v-if="danmuFlag && videoInfo?.disableDanmaku == 0"
                @click="operDammu(false)"
                class="iconfont icon-danmu text-28px hover:c-#00aeec cursor-pointer v-bottom m-r-18px"
              ></span>
              <span
                v-else
                @click="operDammu(true)"
                class="iconfont icon-guanbidanmu text-28px hover:c-#00aeec cursor-pointer v-bottom m-r-18px"
              ></span>
              <span
                class="iconfont icon-danmushezhi text-28px cursor-pointer v-bottom m-r-18px"
                :class="danmuFlag ? 'hover:c-#00aeec' : 'cursor-auto c-#c0c2c5'"
              ></span>

              <!-- 弹幕输入框 -->
              <el-input
                v-model="danmuFrom.content"
                :placeholder="
                  danmuFlag ? '发个友善的弹幕见证当下' : '已关闭弹幕'
                "
                :disabled="!danmuFlag"
                class="input-with-select"
              >
                <template #prepend>
                  <span
                    class="iconfont icon-ziti text-25px cursor-pointer hover:c-#00aeec"
                    @click="danmuConfigFlag = !danmuConfigFlag"
                    :class="danmuConfigFlag ? 'c-#00aeec' : ''"
                  >
                  </span>
                </template>
                <template #append>
                  <el-button
                    @click="sendDanmu()"
                    :disabled="!danmuFlag"
                    :loading="sendDanmuButLoading"
                    class="!h40px !w-70px !b-rd-l-0px"
                  >
                    发送
                  </el-button>
                </template>
              </el-input>
            </div>

            <!-- 弹幕配置 -->
            <div
              class="w-216px bg-[rgba(20,20,20,0.9)] b-rd-2px z-10 translate-x-[-50%] left-33% c-#fff text-12px absolute top--300px"
              v-if="danmuConfigFlag"
            >
              <!-- 字号选择 -->
              <div class="p-[10px_20px]">
                <p class="m-b-10px">字号</p>
                <el-button
                  @click="danmuFrom.fontSize = 16"
                  :color="
                    danmuFrom.fontSize === 16
                      ? '#00aeec'
                      : 'rgba(255, 255, 255, 0.2)'
                  "
                  class="c-#fff border-0 w-80px h-20px"
                >
                  小
                </el-button>
                <el-button
                  @click="danmuFrom.fontSize = 18"
                  :color="
                    danmuFrom.fontSize === 18
                      ? '#00aeec'
                      : 'rgba(255, 255, 255, 0.2)'
                  "
                  class="c-#fff border-0 w-80px h-20px"
                >
                  标准
                </el-button>
              </div>

              <!-- 弹幕位置 -->
              <div class="p-[10px_20px]">
                <p class="m-b-10px">模式</p>

                <div class="flex justify-between gap-10px">
                  <div
                    class="cursor-pointer"
                    @click="danmuFrom.contentPosition = 'scroll'"
                    :class="
                      danmuFrom.contentPosition === 'scroll' ? 'c-#00aeec' : ''
                    "
                  >
                    <span
                      class="iconfont icon-bofangqi-danmugundongkai text-34px"
                    ></span>
                    <p class="m-l-2px">滚动</p>
                  </div>
                  <div
                    class="cursor-pointer"
                    @click="danmuFrom.contentPosition = 'top'"
                    :class="
                      danmuFrom.contentPosition === 'top' ? 'c-#00aeec' : ''
                    "
                  >
                    <span
                      class="iconfont icon-bofangqi-danmudingbukai text-34px"
                    ></span>
                    <p class="m-l-2px">顶部</p>
                  </div>
                  <div
                    class="cursor-pointer"
                    @click="danmuFrom.contentPosition = 'bottom'"
                    :class="
                      danmuFrom.contentPosition === 'bottom' ? 'c-#00aeec' : ''
                    "
                  >
                    <span
                      class="iconfont icon-bofangqi-danmudibukai text-34px"
                    ></span>
                    <p class="m-l-2px">底部</p>
                  </div>
                </div>
              </div>

              <!-- 弹幕颜色 -->
              <div class="p-[10px_20px]">
                <p class="m-b-10px">颜色</p>

                <div class="flex items-center justify-between">
                  <el-input
                    v-model="danmuFrom.color"
                    placeholder="Please input"
                    style="width: 130px"
                    disabled
                  />
                  <!-- 
                :formatter="(value) => `# ${value}`"
                :parser="(value) => value.replace(/\#\s?|(,*)/g, '')" -->
                  <!-- <el-color-picker
                    v-model="danmuFrom.color"
                    :predefine="predefineColors"
                  /> -->
                  <div
                    :style="{ backgroundColor: danmuFrom.color }"
                    class="bg-red w-32px h-32px"
                  ></div>
                </div>
                <div class="grid grid-cols-5 m-t-10px justify-between gap10px">
                  <div
                    v-for="item in predefineColors"
                    @click="danmuFrom.color = item"
                    :style="{ backgroundColor: item }"
                    class="w-20px h-20px cursor-pointer"
                  ></div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 交互栏 -->
        <div
          class="m-t-18px p-b-12px flex justify-between p-x-10px box-border b-b b-b-#e3e5e7 b-b-solid"
        >
          <div class="c-#61666d text-14px flex items-center gap20px">
            <div
              @click="interactiveOperate(1)"
              class="flex items-center gap6px hover:c-#00aeec"
              :class="{ 'c-#00aeec': videoInfo?.likeStatus === 1 }"
            >
              <span class="iconfont icon-icon text-30px cursor-pointer"></span>
              {{ videoInfo?.likeCount }}
            </div>
            <el-popover
              class="box-item"
              content="对本稿件的投币枚数已用完"
              placement="top"
              :show-arrow="false"
              :hide-after="2000"
              :auto-close="2000"
              width="180"
              :visible="videoCoinPopoverVisible"
            >
              <template #reference>
                <div
                  @click="openVideoCoinPopover"
                  class="flex items-center gap6px hover:c-#00aeec"
                  :class="{ 'c-#00aeec': videoInfo?.coinStatus >= 1 }"
                >
                  <span
                    class="iconfont icon-yingbi text-30px cursor-pointer"
                  ></span>
                  {{ videoInfo?.coinCount }}
                </div>
              </template>
            </el-popover>

            <div
              @click="interactiveOperate(3)"
              class="flex items-center gap6px"
            >
              <span
                class="iconfont icon-shoucang1 text-28px cursor-pointer"
              ></span>
              {{ videoInfo?.favoriteCount }}
            </div>
            <div
              @click="interactiveOperate(4)"
              class="flex items-center gap6px"
            >
              <span
                class="iconfont icon-fenxiang_1 text-30px cursor-pointer"
              ></span>
              {{ videoInfo?.shareCount }}
            </div>
          </div>

          <div>
            <span class="iconfont icon-gengduo text-30px c-#61666d"></span>
          </div>
        </div>

        <!-- 简介 -->
        <div class="p-y-20px c-#222 b-b b-b-#e3e5e7 b-b-solid">
          {{ videoInfo?.description }}
        </div>

        <!-- 评论 -->
        <Comments
          :disabled="videoInfo?.disableComment === 1"
          :contentId="videoId"
          :contentType="1"
        ></Comments>
      </div>

      <!-- 右侧个人信息和弹幕列表 -->
      <div class="w-350px desktop:w-411px h-200px">
        <el-skeleton :loading="videoUserInfoLoading" animated>
          <template #template>
            <div class="flex gap20px min-h-78px m-b-10px">
              <el-skeleton-item
                variant="circle"
                style="width: 48px; height: 48px"
              />

              <div>
                <el-skeleton-item variant="h3" style="width: 100px" />
                <el-skeleton-item variant="text" style="width: 100%" />
                <div
                  style="
                    display: flex;
                    align-items: center;
                    justify-items: space-between;
                    height: 16px;
                  "
                >
                  <el-skeleton-item
                    variant="text"
                    style="margin-right: 16px; width: 100px"
                  />
                  <el-skeleton-item variant="text" style="width: 200px" />
                </div>
              </div>
            </div>
          </template>
          <template #default>
            <!-- 个人信息 -->
            <div class="min-h-78px flex items-center gap15px m-b-10px">
              <div
                :style="{
                  backgroundImage: `url(${
                    videoUserInfo?.userVo.avatar || userStore.defaultAvatar
                  })`,
                }"
                @click.stop="router.push('/' + videoUserInfo.id)"
                class="w-48px h-48px b-rd-full pos-relative bg-cover bg-center cursor-pointer"
                @mouseenter="showUserInfo(true, 'pic')"
                @mouseleave="showUserInfo(false, 'pic')"
              >
                <UserProfileCard
                  v-if="
                    userInfoCardVisible &&
                    videoUserInfo?.userVo.userId !==
                      userStore.userInfo.userVo.userId &&
                    activeZone == 'pic'
                  "
                  direction="down"
                  :center="true"
                  :followStatusProp="videoUserInfo?.followUser"
                  @update-data="userProfileCardUpdateData"
                  :item="{
                    createAvatar:
                      videoUserInfo?.userVo.avatar || userStore.defaultAvatar,
                    createByName: videoUserInfo?.userVo.nickName,
                    createUserLevel: videoUserInfo?.currentUserLevel,
                    createFollowNum: videoUserInfo?.followNum,
                    createFansNum: videoUserInfo?.fansNum,
                    createUserSignature: videoUserInfo?.signature,
                    createBy: videoUserInfo?.userVo.userId,
                  }"
                />
              </div>

              <div class="flex-1">
                <div class="flex items-center">
                  <span
                    @mouseenter="showUserInfo(true, 'name')"
                    @mouseleave="showUserInfo(false, 'name')"
                    class="c-#18191c text-15px pos-relative cursor-pointer"
                    @click.stop="router.push('/' + videoUserInfo.id)"
                  >
                    {{ videoUserInfo?.userVo.nickName }}

                    <UserProfileCard
                      v-if="
                        userInfoCardVisible &&
                        videoUserInfo?.userVo.userId !==
                          userStore.userInfo.userVo.userId &&
                        activeZone == 'name'
                      "
                      direction="down"
                      :offset="18"
                      :followStatusProp="videoUserInfo?.followUser"
                      @update-data="userProfileCardUpdateData"
                      :item="{
                        createAvatar:
                          videoUserInfo?.userVo.avatar ||
                          userStore.defaultAvatar,
                        createByName: videoUserInfo?.userVo.nickName,
                        createUserLevel: videoUserInfo?.currentUserLevel,
                        createFollowNum: videoUserInfo?.followNum,
                        createFansNum: videoUserInfo?.fansNum,
                        createUserSignature: videoUserInfo?.signature,
                        createBy: videoUserInfo?.userVo.userId,
                      }"
                    />
                  </span>
                  <span
                    class="iconfont icon-xinxi c-#61666d m-l-20px m-r-5px text-15px"
                  ></span>
                  <span class="c-#61666d text-13px">发消息</span>
                </div>

                <p
                  :title="videoUserInfo?.signature"
                  class="text-13px c-#9499a0 leading-16px m-y-5px line-clamp-1"
                >
                  {{ videoUserInfo?.signature }}
                </p>

                <div flex>
                  <el-button
                    class="w-109px h-30px b-#ff6699 c-#ff6699 hover:bg-#ffecf1 hover:c-#ff6699 hover:b-#ff6699"
                    @click="charge"
                  >
                    充电
                  </el-button>

                  <el-button
                    class="c-#9499a0 h-30px leading-30px flex-1 bg-#e3e5e7 b-#e3e5e7"
                    v-if="
                      videoUserInfo?.followUser &&
                      videoUserInfo?.userVo.userId !==
                        userStore.userInfo.userVo.userId
                    "
                    @click="follow(2)"
                    type="info"
                  >
                    已关注 {{ videoUserInfo?.fansNum }}
                  </el-button>

                  <el-button
                    v-else
                    class="c-#fff h-30px leading-30px bg-#00aeec flex-1 hover:c-#fff hover:bg-#00aeec"
                    @click="follow(1)"
                  >
                    <span
                      class="iconfont icon-jiahao font-600 text-18px m-r-5px"
                    ></span>
                    关注 {{ videoUserInfo?.fansNum }}
                  </el-button>
                </div>
              </div>
            </div>
          </template>
        </el-skeleton>

        <!-- 弹幕列表 -->
        <el-collapse class="!max-h-48px" model-value="1" accordion>
          <el-collapse-item name="1">
            <template #title>
              <span class="c-#18191c text-15px m-x-10px">弹幕列表</span>
              <span class="iconfont icon-gengduo"></span>
            </template>

            <el-scrollbar
              class="h-[calc(var(--w)*9/16-23px)] desktop:h-[calc(var(--w-desktop)*9/16-23px)]"
              style="--w: 668px; --w-desktop: 1086px"
            >
              <div class="c-#61666d text-12px leading-32px flex">
                <div class="w-60px p-l-16px">时间</div>
                <div class="flex-1">弹幕内容</div>
                <div class="w-88px">发送时间</div>
              </div>

              <el-skeleton
                style="width: 100%"
                :loading="danmuListLoading"
                animated
              >
                <template #template>
                  <el-skeleton style="width: 100%" :rows="10" />
                </template>
                <template #default>
                  <div
                    v-for="item in danmuDataList"
                    class="c-#61666d text-12px leading-24px flex cursor-pointer"
                  >
                    <div class="w-60px p-l-16px">
                      {{ DateUtil.formatTime(item.videoTime) }}
                    </div>
                    <div :title="item.content" class="flex-1 line-clamp-1">
                      {{ item.content }}
                    </div>
                    <div class="w-88px">{{ item.createTime.substring(5) }}</div>
                  </div>
                </template>
              </el-skeleton>
            </el-scrollbar>

            <div
              class="h-31px leading-31px text-center bg-#f1f2f3 c-#61666d cursor-pointer b-rd-8px text-12px hover:c-#000"
            >
              查看历史弹幕
            </div>
          </el-collapse-item>
        </el-collapse>
      </div>
    </div>

    <!-- 视频投币弹窗 -->
    <el-dialog v-model="videoCoinDialogVisible" width="500px">
      <p class="c-#18191c text-center">
        给UP主投上
        <span class="text-30px c-#008ac5">
          {{ operVideoForm.coinCount }}
        </span>
        枚硬币
      </p>

      <div class="flex justify-center gap-20px m-t-20px m-b-10px">
        <div
          @click="operVideoForm.coinCount = 1"
          class="p10px b-2px b-dashed b-#ccd0d6 hover:b-#02a0d8 cursor-pointer"
          :class="{
            '!b-#02a0d8': operVideoForm.coinCount === 1,
          }"
        >
          <p>1硬币</p>
          <div
            class="w-195px h-300px bg-no-repeat object-cover bg-[url('/src/assets/img/video/22-coin-ani.png')]"
            :class="{
              'bg-move': operVideoForm.coinCount === 1,
            }"
          ></div>
        </div>
        <div
          v-if="videoInfo?.coinStatus === 0"
          @click="operVideoForm.coinCount = 2"
          class="p10px b-2px b-dashed b-#ccd0d6 hover:b-#02a0d8 cursor-pointer"
          :class="{
            '!b-#02a0d8': operVideoForm.coinCount === 2,
          }"
        >
          <p>2硬币</p>
          <div
            class="w-195px h-300px bg-no-repeat object-cover bg-[url('/src/assets/img/video/33-coin-ani.png')]"
            :class="{
              'bg-move': operVideoForm.coinCount === 2,
            }"
          ></div>
        </div>
      </div>

      <el-checkbox
        label="同时点赞内容"
        v-model:model-value="operVideoForm.coinWhitLikeStatus"
        true-value="0"
        false-value="1"
        checked
      />
      <template #footer>
        <div class="dialog-footer text-center">
          <el-button
            type="primary"
            :loading="videoCoinButLoading"
            @click="handleCoinVideo"
          >
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import { useRoute } from "vue-router";
import { getVideo as getVideoApi, interactiveOperateApi } from "@/api/video";
import type { VideoForm, VideoVO } from "@/api/video/types";
import Player, { Events } from "xgplayer";
import "xgplayer/dist/index.min.css";
import Danmu from "xgplayer/es/plugins/danmu";
import "xgplayer/es/plugins/danmu/index.css";
import type {
  VideoDanmakuForm,
  VideoDanmakuVO,
} from "@/api/videoDanmaku/types";
import {
  listVideoDanmaku as listVideoDanmakuApi,
  addVideoDanmaku as addVideoDanmakuApi,
} from "@/api/videoDanmaku";
import { useUserStore } from "@/store/userStore";
import { DateUtil } from "@/utils/dateUtil";
import {
  addPlayHistory as addPlayHistoryApi,
  getPlayHistoryWithIdType as getPlayHistoryWithIdTypeApi,
} from "@/api/playHistory";
import { getCardUInfo } from "@/api/user/user";
import {
  addUserFollow as addUserFollowApi,
  statusFollow as statusFollowApi,
} from "@/api/userFollow";
import type { UserInfoVo } from "@/api/user/types";
import UserProfileCard from "@/components/UserProfileCard.vue";
import router from "@/router";

const route = useRoute();

const userStore = useUserStore();

// 视频作者信息
const videoUserInfo = ref<UserInfoVo>();
// 视频作者信息加载状态
const videoUserInfoLoading = ref(true);

// 视频投币弹窗
const videoCoinDialogVisible = ref(false);

// 投币按钮加载状态
const videoCoinButLoading = ref(false);

// 路径参数
const videoId = route.params.videoId as string;

// 视频详情
const videoInfo = ref<VideoVO>();

// 视频信息加载状态
const videoInfoLoading = ref(true);

// 弹幕开关
const danmuFlag = ref(true);

// 弹幕配置开关
const danmuConfigFlag = ref(false);

// 发送弹幕按钮加载状态
const sendDanmuButLoading = ref(false);

// 弹幕表单
const danmuFrom = ref<VideoDanmakuForm>({
  videoId: videoId as string,
  content: "",
  color: "#FF3B30",
  fontSize: 16,
  contentPosition: "scroll",
});

// 弹幕数据
const danmuDataList = ref<VideoDanmakuVO[]>([]);

// 用户信息卡片显示状态
const userInfoCardVisible = ref(false);
const activeZone = ref("pic"); // 当前鼠标悬停区域 pic | name

// 视频组件对象
let playerRef = undefined;

// 弹幕操作
const operDammu = (switchFlag: boolean) => {
  danmuFlag.value = switchFlag;

  if (switchFlag) {
    playerRef.plugins.danmu.start();
  } else {
    playerRef.plugins.danmu.stop();
  }
};

// 弹幕预定义颜色
const predefineColors = ref([
  "#FF3B30", // 鲜红 - 强烈、抢眼
  "#FF9500", // 荧光橙 - 醒目、明亮
  "#FFD60A", // 柠檬黄 - 明亮黄，高对比
  "#4CD964", // 荧光绿 - 鲜亮柔和绿
  "#5AC8FA", // 天蓝色 - 冷静而亮眼
  "#007AFF", // 苹果蓝 - 强烈科技感
  "#5856D6", // 荧光紫 - 个性鲜明
  "#FF2D55", // 玫红红 - 活力女性向
  "#FF5E3A", // 番茄橘 - 热情洋溢
  "#34C759", // 活力绿 - Apple风格绿色
]);

// 弹幕列表加载状态
const danmuListLoading = ref(true);

// 发送弹幕
const sendDanmu = async () => {
  if (playerRef.ended) {
    ElMessage.warning("哇哦，视频播放已Over");
    return;
  }

  if (danmuFrom.value.content == "") {
    ElMessage.warning("请输入弹幕内容");
    return;
  }

  sendDanmuButLoading.value = true;

  let res = await addVideoDanmakuApi(danmuFrom.value);

  danmuFrom.value.content = "";

  getDanmuList();

  sendDanmuButLoading.value = false;

  playerRef.plugins.danmu.sendComment({
    duration: 5000, //弹幕持续显示时间,毫秒(最低为5000毫秒)
    id: new Date().getTime(), //弹幕id，需唯一
    start: danmuFrom.value.videoTime * 1000, //弹幕出现时间, 单位：ms 毫秒
    txt: res.data.content,
    style: {
      //弹幕自定义样式
      color: danmuFrom.value.color,
      fontSize: `${danmuFrom.value.fontSize}px`,
      // border: "solid 1px #ff9500",
      borderRadius: "50px",
      padding: "5px 11px",
      backgroundColor: "rgba(255, 255, 255, 0.1)",
    },
  });
};

// 获取弹幕数据
const getDanmuList = async () => {
  let danmuRes = await listVideoDanmakuApi({ videoId: videoId });
  danmuDataList.value = danmuRes.rows;

  if (danmuDataList) {
    playerRef.plugins.danmu.updateComments(
      danmuDataList.value.map((item) => {
        return {
          duration: 5000, //弹幕持续显示时间,毫秒(最低为5000毫秒)
          id: item.id, //弹幕id，需唯一
          start: item.videoTime * 1000, //弹幕出现时间, 单位：ms 毫秒
          txt: item.content,
          style: {
            //弹幕自定义样式
            color: item.color,
            fontSize: `${item.fontSize}px`,
            // border: "solid 1px #ff9500",
            borderRadius: "50px",
            padding: "5px 11px",
            backgroundColor: "rgba(255, 255, 255, 0.1)",
          },
        };
      })
    );
  }
  danmuListLoading.value = false;
};

// 无法投币时消息提示控制
const videoCoinPopoverVisible = ref(false);

// 打开投币前触发
const openVideoCoinPopover = () => {
  videoCoinPopoverVisible.value = videoInfo.value.coinStatus === 2;
  videoCoinDialogVisible.value =
    videoInfo.value.coinStatus !== 2 ? true : false;
  setTimeout(() => {
    videoCoinPopoverVisible.value = false;
  }, 2000);
};

const handleCoinVideo = async () => {
  videoCoinButLoading.value = true;
  await interactiveOperate(2);
  videoCoinDialogVisible.value = false;
  videoCoinButLoading.value = false;
};

// 交互操作表单对象
const operVideoForm = ref<VideoForm>({
  id: videoId,
  coinCount: 1,
  coinWhitLikeStatus: 0,
});

// 交互操作 1-点赞 2-投币 3-收藏 4-分享
const interactiveOperate = async (type: number) => {
  if (type > 2) {
    ElMessage.warning("该功能暂未开放");
    return;
  }

  operVideoForm.value.operateType = type;
  await interactiveOperateApi(operVideoForm.value);
  videoInfo.value = (await getVideoApi(videoId as string)).data;
};

// 充电
const charge = () => {
  ElMessage.warning("充电功能暂未开放");
};

// 关注方法 操作类型 1-关注 2-取消关注
const follow = async (operateType: number) => {
  if (videoUserInfo.value.userVo.userId === userStore.userInfo.userVo.userId) {
    ElMessage.warning("无法关注自己");
    return;
  }

  await addUserFollowApi({
    followingId: videoUserInfo.value.id.toString(),
    operateType: operateType,
  });
  videoUserInfo.value.followUser = !videoUserInfo.value.followUser;
  videoUserInfo.value.fansNum =
    operateType === 1
      ? videoUserInfo.value.fansNum + 1
      : videoUserInfo.value.fansNum - 1;
};

// 显示用户信息卡片
const showUserInfo = (flag: boolean, zone: string) => {
  userInfoCardVisible.value = flag;
  activeZone.value = zone;
};

// 接收用户卡片子组件数据
const userProfileCardUpdateData = (
  followStatus: boolean,
  operateType: number
) => {
  videoUserInfo.value.followUser = followStatus;
  videoUserInfo.value.fansNum =
    operateType === 1
      ? videoUserInfo.value.fansNum + 1
      : videoUserInfo.value.fansNum - 1;
};

onMounted(async () => {
  // 获取视频详细信息
  let res = await getVideoApi(videoId as string);
  videoInfo.value = res.data;

  videoInfoLoading.value = false;

  let playHistory = await getPlayHistoryWithIdTypeApi(videoId, 1);

  getCardUInfo(videoInfo.value.createBy).then((res) => {
    videoUserInfo.value = res.data;
    videoUserInfoLoading.value = false;
  });

  // 初始化播放器
  playerRef = new Player({
    id: "mse",
    autoplay: true, // 自动播放
    volume: 0.3, // 音量
    url: videoInfo.value.fileUrl, // 视频文件
    poster: videoInfo.value.coverUrl, // 封面图片
    playsinline: true, // 内联
    pip: true, // 画中画
    startTime:
      playHistory.data && playHistory.data.isCompleted == 0
        ? playHistory.data.playDuration
        : 0, // 初始起播时间
    thumbnail: JSON.parse(videoInfo.value.thumbnailInfo),
    plugins: [Danmu],
    fluid: true,
    danmu: {
      comments: [], // 弹幕数据
      area: {
        start: 0,
        end: 0.5,
      },
      closeDefaultBtn: true,
    },
    dynamicBg: {
      disable: false,
    },
    whitelist: [""],
  });

  // 获取弹幕数据
  getDanmuList();

  // 节流标记
  let lastSendTime = 0;
  playerRef.on(Events.TIME_UPDATE, (data) => {
    // data结构如下
    /**
     * data = {
     *   action: String,        // 用户行为
     *   pluginName: String,    // 从哪个插件触发
     *   props: [{              // 发生变化的属性列表
     *     props: String,       // 发生变化的属性
     *     from: any,           // 变化前的值
     *     to: any              // 变化后的值
     *   }],
     *   event: Event,          // 事件
     *   currentTime: Number,   // 当前播放时间
     *   duration: Number,      // 当前播放器时长
     *   ended:  Boolean,        // 是否播放结束
     *   paused:  Boolean,       // 是否暂停
     * }
     */
    danmuFrom.value.videoTime = data.currentTime.toFixed(0);

    // 播放记录
    if (Date.now() - lastSendTime > 3000 || data.paused || data.ended) {
      addPlayHistoryApi({
        contentId: videoId,
        contentType: 1,
        playDuration: data.currentTime.toFixed(),
        isCompleted: data.ended ? 1 : 0,
      });
      lastSendTime = Date.now();
    }
  });
});
</script>

<style scoped lang="less">
::v-deep .input-with-select {
  height: 40px;
}

::v-deep .input-with-select .el-input__wrapper {
  box-shadow: inset 0 1px 0 0
      var(--el-input-border-color, var(--el-border-color)),
    inset 0 -1px 0 0 var(--el-input-border-color, var(--el-border-color)),
    inset -1px 0 0 0 var(--el-input-border-color, var(--el-border-color));
  padding-left: 0px;
}

::v-deep .input-with-select .el-input-group__prepend {
  border-top-left-radius: 10px;
  border-bottom-left-radius: 10px;
}

::v-deep .input-with-select .el-input-group__append {
  background-color: #00aeec;
  color: #fff;
  box-shadow: none;
  border-top-right-radius: 10px;
  border-bottom-right-radius: 10px;
}

::v-deep .input-with-select .el-input-group__prepend {
  padding: 0 10px;
  background-color: #fff;
}

// 文本域禁止拖拽
:deep(.el-textarea__inner) {
  resize: none;
}

::v-deep .el-collapse-item__header {
  background-color: #f1f2f3;
}

::v-deep .el-collapse-item__wrap {
  border-bottom: 0px;
}
::v-deep .el-collapse-item__content {
  padding-bottom: 0px;
}

@keyframes sprite {
  0% {
    background-position: 0 0;
  }
  100% {
    background-position: -4488px 0;
  }
}

.bg-move {
  animation: sprite 0.6s steps(24) infinite;
}
</style>
